﻿using Google.Protobuf.Collections;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class AddMomentPanel : AppUI
{
    public Text topicText;
    public InputField inputField;
    public UITouchObject inputFieldTouchObject;
    List<Texture2D> m_Photos = new List<Texture2D>();

    public MomentPhotoItem[] photos;
    public GridLayoutGroup photoGrisGroup;

    int m_momentStatus;
    string m_Topic;

    public RectTransform bottomTrans;

    public string[] topics;
    public Transform topicItemsParent;
    List<TopicItem> m_TopicItems = new List<TopicItem>();
    public TopicItem topicItemPref;

    public RectTransform bottomDownPos;

    ZUIAnimTools m_ZUIAnimTools;
    ZUIAnimTools animTools
    {
        get
        {
            if (m_ZUIAnimTools == null)
                m_ZUIAnimTools = gameObject.AddComponent<ZUIAnimTools>();

            return m_ZUIAnimTools;
        }
    }

    public override void Awake()
    {
        topicItemPref.gameObject.SetActive(false);
        inputField.onValueChanged.AddListener(OnInputValueChanged);
        //inputField.OnPointerDown.AddListener(OnInputBeginDrag);
        inputField.onEndEdit.AddListener(OnInputEndEdit);
        inputFieldTouchObject.onPointerDownBegin = OnInputFieldTouchDown;
    }


    void OnEnable()
    {
        interacted = false;
        inputField.text = "";

        UnityFunctions.ClearList(m_TopicItems);
        for(int i = 0; i < this.topics.Length; i++)
        {
            var item = Instantiate(topicItemPref, topicItemsParent);
            item.gameObject.SetActive(true);
            item.onClick = this.OnSelectTopicItem;
            item.text.text = $"# {topics[i]}";

            m_TopicItems.Add(item);
        }
       
        StartCoroutine(UnityFunctions.AdjustItemsLayout(topicItemsParent.transform));

        for (int i = 0; i < m_Photos.Count; i++)
        {
            if (m_Photos[i] != null)
                GameObject.DestroyImmediate(m_Photos[i]);

        }
        m_Photos.Clear();

        RefreshPhotos();
    }

    void OnInputFieldTouchDown(Vector2 pos)
    {
        animTools.RectMove(this.bottomTrans, Vector2.zero, .2f);
    }

    private void OnInputValueChanged(string value)
    {
        GameDebug.Log($"OnInputValueChanged:{value}");
    }
    private void OnInputEndEdit(string arg0)
    {
        DoActionDelay.DelayAction(0.02f, () =>
        {
            if(!interacted)
                animTools.RectMove(this.bottomTrans, this.bottomDownPos.anchoredPosition, .2f);
        });
    }

    private void OnSelectTopicItem(TopicItem item)
    {
        m_Topic = item.text.text.Replace("# ", "");
        this.topicText.text = m_Topic;

        foreach (TopicItem topicItem in this.m_TopicItems)
        {
            if (topicItem != item)
                topicItem.gameObject.SetActive(true);
            else
                topicItem.gameObject.SetActive(false);
        }

        StartCoroutine(UnityFunctions.AdjustItemsLayout(topicText.transform.parent));
    }

    void RefreshPhotos()
    {
        int photoCount = 0;
        
        for (int i = 0; i < 9; i++)
        {
            if (i >= m_Photos.Count)
            {
                photos[i].gameObject.SetActive(false);
                continue;
            }

            if (m_Photos[i] != null)
            {
                photoCount++;
                photos[i].Init(m_Photos[i]);
                photos[i].gameObject.SetActive(true);
                photos[i].onClickClose = OnRemovePhoto;
            }
            else
            {
                photos[i].gameObject.SetActive(false);
            }
        }

        float photoSize = 280;
        if (photoCount <= 1)
        {
            photoSize = 500;
            this.photoGrisGroup.cellSize = new Vector2(photoSize, photoSize);
        }
        else if (photoCount <= 2)
        {
            photoSize = 400;
            this.photoGrisGroup.cellSize = new Vector2(photoSize, photoSize);
        }
        else
        {
            photoSize = 280;
            this.photoGrisGroup.cellSize = new Vector2(280, 280);
        }
        for(int i = 0; i < photoCount; i++)
        {
            photos[i].SetImgSize(photoSize);
        }
    }

    private void OnRemovePhoto(MomentPhotoItem item)
    {
        Texture2D tex = item.texture2D;
        DestroyImmediate(tex);

        m_Photos.Remove(item.texture2D);
        RefreshPhotos();
    }

    public void OnDraopdown(int id)
    {
        GameDebug.Log($"OnDraopdown:{id}");
    }

    public void OnClickAddPhoto()
    {
        interacted = true;

        if (m_Photos.Count >= 9) return;

        EditPhotoItem.LoadImg((newtexture) =>
        {
            m_Photos.Add(newtexture);
            RefreshPhotos();

            StartCoroutine(UnityFunctions.AdjustItemsLayout(photoGrisGroup.transform));

            interacted = false;
        });
    }

    bool interacted;
    public void OnClickSubmit()
    {
        if (interacted)
            return;

        interacted = true;


        Tex[] texs = m_Photos.Map(e =>
        {
            byte[] bytes = e.EncodeToJPG(80);
            return new Tex(bytes, e.width, e.height);
         }).AsArray();

        RequestServerController.instance.ReqAddMoment(MGame.instance.MUser.id, UnityFunctions.GetTimeStampSeconds(),
            this.inputField.text, "", m_Topic, m_momentStatus, texs,(moment)=>
            {
                GameDebug.Log($"ReqAddMoment end");

                interacted = false;
                UserHomePanel userHome = UIController.GetUI<UserHomePanel>() as UserHomePanel;
                userHome.Refresh(moment);

                UserMomentsPanel userMoments = UIController.GetUI<UserMomentsPanel>() as UserMomentsPanel;
                userMoments.Refresh(moment);

                interacted = false ;
                GoBack();
            });

    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
